package com.bfmet;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

import com.bfmet.common.DAOService;
import com.bfmet.common.base.UtilBase;
import com.bfmet.crawler.HotSpider;
import com.bfmet.crawler.IndustrySpider;
import com.bfmet.crawler.MetalSpider;
import com.bfmet.crawler.NewsSpider;
import com.bfmet.crawler.PolicySpider;
import com.bfmet.crawler.PriceSpider;

@WebListener
public class StartupListener extends UtilBase implements
		ServletContextListener, HttpSessionListener {

	@Override
	public void contextDestroyed(ServletContextEvent arg0) {
		try {
			// super.contextDestroyed(arg0);
			// PreJobs.getInstance().stop();
			DAOService.getEM().getEntityManagerFactory().close();
		} catch (Exception ex) {
			logException(ex);
		}
	}

	@Override
	public void contextInitialized(ServletContextEvent sce) {
		try {
			// super.contextInitialized(sce);
			ScheduledExecutorService pool = Executors
					.newScheduledThreadPool(100);
			pool.scheduleAtFixedRate(new NewsSpider(), 0, 2, TimeUnit.HOURS);
			pool.scheduleAtFixedRate(new PriceSpider(), 0, 2, TimeUnit.HOURS);
			pool.scheduleAtFixedRate(new PolicySpider(), 0, 2, TimeUnit.HOURS);
			pool.scheduleAtFixedRate(new IndustrySpider(), 0, 2, TimeUnit.HOURS);
			pool.scheduleAtFixedRate(new HotSpider(), 0, 2, TimeUnit.HOURS);

			pool.scheduleAtFixedRate(new MetalSpider(), 0, 2, TimeUnit.HOURS);
		} catch (Exception ex) {
			this.logException(ex);
		}
	}

	@Override
	public void sessionCreated(HttpSessionEvent event) {
		// super.sessionCreated(event);
	}

	@Override
	public void sessionDestroyed(HttpSessionEvent event) {
		// super.sessionDestroyed(event);
	}
}
